import React, { useEffect, useState } from 'react';
import { Table, Input, InputNumber, Popconfirm, Form, Button } from 'antd';
import { getAdminList } from '../../../../api'

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

const EditableTable = () => {

  const [form] = Form.useForm();
  const [data, setData] = useState([]);
  // 请求数据并设置
  const getAdminListAndSetOriginData = async () => {
    // 请求数据
    const resp = await getAdminList()
    // 设置
    setData(resp.data.data)
  }
  // 副作用函数
  // 不依赖任何数据 只会在挂载结束后 执行一次 类似与 componentDidMount
  useEffect(() => {
    getAdminListAndSetOriginData()
  }, [])
  const [editingKey, setEditingKey] = useState('');

  const isEditing = (record) => record.key === editingKey;

  const edit = (record) => {
    form.setFieldsValue({
      name: '',
      age: '',
      address: '',
      ...record,
    });
    setEditingKey(record.key);
  };

  const cancel = () => {
    setEditingKey('');
  };

  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        setEditingKey('');
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  const handleDelete = (record) => {
    
    const newData = data.filter(item => item.key !== record.key)
    setData(newData)
  }

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      width: '25%',
      editable: true,
    },
    {
      title: '年龄',
      dataIndex: 'age',
      width: '15%',
      editable: true,
    },
    {
      title: '地址',
      dataIndex: 'address',
      width: '40%',
      editable: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) => {
        const editable = isEditing(record);
        return (
          <div>
            {editable ? (
              <span>
                <Button
                  type="paimary"
                  danger
                  onClick={() => save(record.key)}
                  style={{
                    marginRight: 8,
                  }}
                >
                  Save
                </Button>
                <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
                  <Button>取消</Button>
                </Popconfirm>
              
              </span>
            ) : (
              <Button disabled={editingKey !== ''} onClick={() => edit(record)}>
                Edit
              </Button>
            )}
            <Popconfirm placement="top" title={'确认删除吗？'} onConfirm={() => handleDelete(record) } okText="删除" cancelText="取消">
              <Button type="primary" danger>
                删除
              </Button>
           </Popconfirm>
              
          </div>
        )
      },
    },
  ];
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === 'age' ? 'number' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  return (
    <Form form={form} component={false}>
      <Table
        components={{
          body: {
            cell: EditableCell,
          },
        }}
        bordered
        dataSource={data}
        columns={mergedColumns}
        rowClassName="editable-row"
        pagination={{
          onChange: cancel,
        }}
      />
    </Form>
  );
};

export default EditableTable